package account

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"qycms/controllers"
	"qycms/models/auth"
	"qycms/untils"
	"strconv"
	"strings"
)

type AccountController struct {
	controllers.BaseController
}
/**
 * 用户列表
 */
func (this *AccountController) Index()  {
	this.TplName = "account/index.html"
}

/**
 * 用户列表数据
 */
func (this *AccountController) UserList()  {

	//分页计算
	currentPage,err := this.GetInt("page",1)
	pagePerNum,_ := this.GetInt("limit",20)
    if(err != nil ){
		currentPage = 1
	}
	offsetNum := pagePerNum * (currentPage - 1)

	//数据查询
	var count int64 = 0
	users := []auth.User{}

	O := orm.NewOrm()
	q := O.QueryTable("sys_user")

    keyword := this.GetString("key")
	if keyword != ""{
		q = q.Filter("truename__icontains",keyword)
	}

	count,_ = q.Filter("is_delete",0).Count()
    q.Filter("is_delete",0).Limit(pagePerNum).Offset(offsetNum).All(&users)

	for _, userd := range users {
		O.LoadRelated(&userd, "Role")
	}

    this.Data["json"] = untils.ListJson(count,users)
	this.ServeJSON()
	this.StopRun()
}

/**
 * 用户添加页面
 */
func (this *AccountController) AddUserView()  {
	o := orm.NewOrm()
	roles := []auth.Role{}
	o.QueryTable("sys_role").Filter("is_active",1).Filter("is_delete",0).All(&roles)
	this.Data["role"] = roles
	this.TplName = "account/add.html"
}

/**
 * 用户添加操作
 */
func (this *AccountController) AddUser()  {
    //接收参数
	roleID := this.GetString("roleID")
	username := this.GetString("username")
	truename := this.GetString("truename")
	password := this.GetString("password")
	confirmpass := this.GetString("confirmpass")
	phone := this.GetString("phone")
	email := this.GetString("email")
	age,_ := this.GetInt("age")
	gender,_ := this.GetInt("gender")
	is_active,_ := this.GetInt("is_active")
	address := this.GetString("address")
	mark := this.GetString("mark")

    //数据验证
    valid := validation.Validation{}
	valid.Required(roleID,"roleID").Message("请选择角色")
    valid.Required(username,"username").Message("用户名不能为空")
	valid.Required(truename,"truename").Message("真实姓名不能为空")
	valid.Required(password,"password").Message("密码不能为空")
	valid.Required(confirmpass,"password2").Message("确认密码不能为空")
	valid.Required(phone,"phone").Message("用户手机号不能为空")
	valid.Mobile(phone,"phone").Message("用户手机号格式不正确")
	valid.Required(email,"email").Message("邮箱不能为空")
	valid.Email (email,"email").Message("邮箱格式不正确")
	valid.Required(age,"age").Message("用户年龄不能为空")
	valid.Numeric(age,"age").Message("用户年龄必须是数字")
	valid.Range(age,20,100,"age").Message("用户年龄必须在20到100岁之间")
	valid.Required(gender,"gender").Message("用户性别不能为空")
	valid.Required(is_active,"is_active").Message("用户状态不能为空")
	valid.Required(address,"address").Message("用户地址不能为空")
	valid.Required(mark,"mark").Message("备注不能为空")

    if password != confirmpass {
    	this.Err(2001,"密码输入确认不一致",nil)
	}

	o := orm.NewOrm()
	//用户账号唯一性验证
    isusername := o.QueryTable("sys_user").Filter("username",username).Filter("is_delete",0).Exist()

	if isusername {
		this.Err(2001,"用户账号已经存在",nil)
	}

	//用户手机号唯一性验证
	isphone := o.QueryTable("sys_user").Filter("phone",phone).Filter("is_delete",0).Exist()
	if isphone {
		this.Err(2001,"用户手机号已经存在",nil)
	}

	//用户email唯一性验证
	isemail := o.QueryTable("sys_user").Filter("email",email).Filter("is_delete",0).Exist()
	if isemail {
		this.Err(2001,"用户Email已经存在",nil)
	}

	//密码加密
	new_password := untils.GetMd5Str(password)
	phone_int64,_ := strconv.ParseInt(phone,10,64)
    //绑定到模型
    user := auth.User{
         UserName: username,
         Password: new_password,
         TrueName: truename,
         Age: age,
         Gender: gender,
         Phone: phone_int64,
         Email: email,
         Address: address,
         Mark: mark,
         IsActive: is_active,
	}

    _ ,err := o.Insert(&user)

	if err != nil {
		this.Err(2001,"操作失败",nil)
	}else{
		this.Suc(nil)
	}
}

/**
 * 用户更新页面
 */
func (this *AccountController) EditUserView()  {
    id,_ := this.GetInt("id")

    //role全部角色
	o := orm.NewOrm()
	roles := []auth.Role{}
	o.QueryTable("sys_role").Filter("is_active",1).Filter("is_delete",0).All(&roles)

	//用户信息
	user := auth.User{}
	o.QueryTable("sys_user").Filter("id",id).Filter("is_delete",0).One(&user)


	//用户属于的角色
	//var myrole []orm.Params
	//o.QueryTable("sys_role_sys_users").Filter("sys_user_id",id).One(&myrole)

	this.Data["role"] = roles
	//this.Data["myrole"] = myrole
	this.Data["user"] = user
	this.TplName = "account/edit.html"
}
/**
 * 用户更新操作
 */
func (this *AccountController) UpdateUser()  {
	//接收参数
	ID := this.GetString("Id")
	roleID := this.GetString("roleID")
	username := this.GetString("username")
	truename := this.GetString("truename")
	password := this.GetString("password")
	confirmpass := this.GetString("confirmpass")
	phone := this.GetString("phone")
	email := this.GetString("email")
	age,_ := this.GetInt("age")
	gender,_ := this.GetInt("gender")
	is_active := this.GetString("is_active")
	address := this.GetString("address")
	mark := this.GetString("mark")

	//数据验证
	valid := validation.Validation{}
	valid.Required(ID,"Id").Message("请选择修改的数据")
	valid.Required(roleID,"roleID").Message("请选择角色")
	valid.Required(username,"username").Message("用户名不能为空")
	valid.Required(truename,"truename").Message("真实姓名不能为空")
	valid.Required(password,"password").Message("密码不能为空")
	valid.Required(confirmpass,"password2").Message("确认密码不能为空")
	valid.Required(phone,"phone").Message("用户手机号不能为空")
	valid.Mobile(phone,"phone").Message("用户手机号格式不正确")
	valid.Required(email,"email").Message("邮箱不能为空")
	valid.Email (email,"email").Message("邮箱格式不正确")
	valid.Required(age,"age").Message("用户年龄不能为空")
	valid.Numeric(age,"age").Message("用户年龄必须是数字")
	valid.Range(age,20,100,"age").Message("用户年龄必须在20到100岁之间")
	valid.Required(gender,"gender").Message("用户性别不能为空")
	valid.Required(is_active,"is_active").Message("用户状态不能为空")
	valid.Required(address,"address").Message("用户地址不能为空")
	valid.Required(mark,"mark").Message("备注不能为空")


	o := orm.NewOrm()
	//用户账号唯一性验证
	isusername := o.QueryTable("sys_user").Exclude("id",ID).Filter("username",username).Filter("is_delete",0).Exist()

	if isusername {
		this.Err(2001,"用户账号已经存在",nil)
	}

	//用户手机号唯一性验证
	isphone := o.QueryTable("sys_user").Exclude("id",ID).Filter("phone",phone).Filter("is_delete",0).Exist()
	if isphone {
		this.Err(2001,"用户手机号已经存在",nil)
	}

	//用户email唯一性验证
	isemail := o.QueryTable("sys_user").Exclude("id",ID).Filter("email",email).Filter("is_delete",0).Exist()
	if isemail {
		this.Err(2001,"用户Email已经存在",nil)
	}

	//绑定到模型
	var new_is_active int
	if is_active == "on"{
        new_is_active = 1
	}else{
		new_is_active = 0
	}

	phone_int64,_ := strconv.ParseInt(phone,10,64)
	user := orm.Params{
		"username": username,
		"truename": truename,
		"age": age,
		"gender": gender,
		"phone": phone_int64,
		"email": email,
		"address": address,
		"mark": mark,
		"isActive": new_is_active,
	}

	_ ,err := o.QueryTable("sys_user").Filter("id",ID).Update(user)

	if err != nil {
		this.Err(2001,"操作失败",nil)
	}else{
		this.Suc(nil)
	}
}

/**
 * 删除用户
 */
func (this *AccountController) DelUser()  {
	 //接收参数
    ids := this.GetString("ids");
    new_ids := ids[:len(ids)]
    id_arr := strings.Split(new_ids,",")

    //数据更新
	o := orm.NewOrm()
	qs := o.QueryTable("sys_user")
	for _,v :=range id_arr{
		id_int := untils.StrToInt(v)
		qs.Filter("id",id_int).Update(orm.Params{
			"is_delete":1,
		})
	}
	this.Suc(nil)
}